package dymnd.plugin;

import java.io.*;
import java.net.*;
import java.util.*;
public class PluginLoader {
	
	/*
	 * This file is in DESPERATE need of refactoring!!!! 
	 */
	
	public static Plugin[] loadPlugins(String f)	{
		Plugin[] loadedPlugins = null;
		File pluginDir = new File(f);
		try	{
			
			File[] pluginDirs = pluginDir.listFiles();
			ArrayList<File> pluginDirectories = new ArrayList<File>(pluginDirs.length);
			for(int i = 0; i < pluginDirs.length; i++)	{
				if(pluginDirs[i].isDirectory())	{
					pluginDirectories.add(pluginDirs[i]);
					
				}
			}
			pluginDirs = pluginDirectories.toArray(new File[pluginDirectories.size()]);
			
			URL[] plugindirURL = new URL[1];
			plugindirURL[0] = pluginDir.toURL();
			
			URLClassLoader loader = new URLClassLoader(plugindirURL);
			
			Plugin[] pluginList = new Plugin[pluginDirs.length];
			
			for(int i = 0; i < pluginDirs.length; i++)	{
				pluginList[i] =(Plugin) loader.loadClass("plugins." + pluginDirs[i].getName() + ".EPC").newInstance();
			}
			loadedPlugins = pluginList;
			 
			//clean up!
			loader = null;
			plugindirURL = null;
			//pluginList = null;
			pluginDir = null;
			
		}	catch (Exception x)	{
			x.printStackTrace();
		}
		
		System.gc(); // Garbage Collect
		
		return loadedPlugins;
	}
	
}
